package com.baorant.springdemo1.service;

import com.baorant.springdemo1.domain.User;
import com.baorant.springdemo1.mapper.UserMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class UserService {
    private final UserMapper userMapper;

    // 推荐使用构造器注入
    public UserService(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    public User findUsersByName(String name) {
        if (name == null || name.trim().isEmpty()) {
            throw new IllegalArgumentException("用户名不能为空");
        }
        return (User) userMapper.findByName(name);
    }

    public User createUser(String name, String password) {
        if (name == null || name.trim().isEmpty()) {
            throw new IllegalArgumentException("用户名不能为空");
        }
        if (password == null || password.trim().isEmpty()) {
            throw new IllegalArgumentException("密码不能为空");
        }

        User user = new User();
        user.setName(name);
        user.setPassword(password);
        int affectedRows = userMapper.insert(user);
        if (affectedRows == 0) {
            throw new RuntimeException("创建用户失败");
        }

        return user;
    }

    public User createAndFindUsers(String name) {
        User newUser = createUser(name, null);
        return findUsersByName(newUser.getName());
    }
}
